import fs from 'fs'
import path from 'path'
import xlsx from 'xlsx'
import chalk from 'chalk'
import ora from 'ora'
const transformLanguage = (rootDirectory, languageConfig) => {
	// 输出配置
	let result = languageConfig.output.map((config) => {
		const { key, value } = config
		// const outputPath = path.join(
		//   rootDirectory,
		//   `/src/generated/lang/`,
		//   `${key}.ts`
		// );
		const outputPath = path.join(rootDirectory, `/src/generated/lang/`, `${key}.ts`).replace(/\\/g, '/')
		ensureDirectoryExists(path.dirname(outputPath))
		// fs.ensureDirSync;
		// fs.ensureDirSync(path.dirname(outputPath));
		return { key, value, path: outputPath, object: {} }
	})

	console.log('result', result)

	console.log('%c [  ]-16', 'font-size:13px; background:pink; color:#bf2c9f;', languageConfig.input)
	// 根据 input文件的fileName，来获取完整文件地址，以此读取xlsx每一条
	const xlsxFiles = languageConfig.input.filter((file) => file.fileName.endsWith('.xlsx')).map((item) => item.fileName)
	let langDir = path.join(rootDirectory, '/tools/lang/')
	console.log('xlsxFiles', xlsxFiles)
	// 开始做循环，解析每一个表
	xlsxFiles.forEach((fileName) => {
		const filePath = path.join(langDir, fileName)
		console.log('filePath', filePath)
		// 根据路径，读取文件
		const workbook = xlsx.read(fs.readFileSync(filePath), { type: 'array' })
		const fileIndex = languageConfig.input.findIndex((item) => item.fileName === fileName)
		const sheetNames = languageConfig.input[fileIndex].sheetNames
		console.log('sheetNames', sheetNames)
		sheetNames.forEach((sheetName) => {
			const sheet = workbook.Sheets[sheetName]
			const sheetData = xlsx.utils.sheet_to_json(sheet)
			// console.log('sheetData',sheetData)
			// 此时获取到了xlsx的json 数据，怎么跟输出配置做匹配呢？
			sheetData.forEach((json) => {
				console.log('json', json)
				// 匹配到key，把value 赋值给对应的key
				result.forEach((config) => {
					config.object[json['key']] = json[config.value]
				})
				console.log('result', result)
			})
		})
	})
	// 生成 TypeScript 文件
	result.forEach((config) => {
		const { key, value, path, object } = config
		// const content = `export default\n{ \n${toSingleQuotedValues(object)}};`;
		const content = `export default ${JSON.stringify(object, null, 2)};`
		console.log('path', path)
		fs.writeFileSync(path, content)
	})
}
/**
 * 辅助函数，将对象的值包裹在单引号中
 * @param obj
 * @returns
 */
function toSingleQuotedValues(obj) {
	console.log('%c [  ]-131', 'font-size:13px; background:pink; color:#bf2c9f;', obj)
	const entries = Object.entries(obj).map(([key, value]) => {
		const quotedValue = value?.includes("'") ? `${value}` : `'${value}'`
		return `  ${key}: ${quotedValue}`
	})
	return entries.join(',\n')
}
/**
 * 辅助函数，确保输出目录存在，不存在则创建
 * @param directoryPath 路径
 */
function ensureDirectoryExists(directoryPath) {
	try {
		fs.mkdirSync(directoryPath, { recursive: true })
	} catch (error) {
		handleError(chalk.red.bold(`创建目录失败: ${directoryPath}: ${error}`))
	}
}
const xlsxTransformLanguage = () => {
	// 获取当前目录
	let rootDirectory = process.cwd()
	let pathJson = path.join(rootDirectory, '/test.json')

	console.log('%c [  ]-11', 'font-size:13px; background:pink; color:#bf2c9f;', pathJson)
	// 获取json 文件
	let languageConfig = JSON.parse(fs.readFileSync(path.join(rootDirectory, '/tools/lang/lang-config.json'), 'utf-8'))
	console.log(languageConfig)
	transformLanguage(rootDirectory, languageConfig)
}
xlsxTransformLanguage()
